﻿using System;
using System.Linq;
using System.Threading.Tasks;
using Volo.Abp;
using Xms.Abp.Application.Services;
using Xms.Abp.Authorization;
using Xms.Abp.Domain.Repositories;

namespace BackgroundJobManagement;

[PermissionsUse(typeof(BackgroundSchedulePermissions))]
public class BackgroundScheduleAppService : XmsCrudAppService<BackgroundScheduleEntity, BackgroundScheduleResult, Guid, BackgroundSchedulesPagedParameter, BackgroundScheduleCreateParameter, BackgroundScheduleUpdateParameter>, IBackgroundScheduleAppService
{
    public BackgroundScheduleAppService(IXmsRepository<BackgroundScheduleEntity, Guid> repository) : base(repository)
    {
    }

    protected override async Task<IQueryable<BackgroundScheduleEntity>> CreateFilteredQueryAsync(BackgroundSchedulesPagedParameter input)
    {
        var query = await base.CreateFilteredQueryAsync(input);
        query = query.WhereIf(!input.Filter.IsNullOrWhiteSpace(), r => r.Name.Contains(input.Filter) || r.DisplayName.Contains(input.Filter));
        query = query.WhereIf(input.MultiTenancySides.HasValue, r => r.MultiTenancySides == input.MultiTenancySides);
        return query;
    }

    protected override Func<BackgroundScheduleCreateParameter, BackgroundScheduleEntity> EntityCreator => input => new BackgroundScheduleEntity(GuidGenerator.Create());

    protected override async Task BeforeUpdateAsync(BackgroundScheduleEntity entity, BackgroundScheduleUpdateParameter input)
    {
        await base.BeforeUpdateAsync(entity, input);
        entity.ModificationTime = DateTime.Now;
    }

    public async Task ExecuteAsync(Guid id)
    {
        var schedule = await (await Repository.GetQueryableAsync()).FirstOrDefaultAsync(r => r.Id == id);
        if (schedule == null)
        {
            throw new UserFriendlyException("执行计划不存在");
        }
        schedule.NextExecuteTime = Clock.Now;
        await Repository.UpdateAsync(schedule, true);
    }
}
